import React, { Component } from "react";
import { connect } from 'react-redux'
import { messages } from "share/common";
import { Button, Radio, message, Spin } from 'antd'
import Condition from "components/condition";
import Table from "components/table";
import credentialService from "./credential-definition-service";
import ListSelector from "components/list-selector";
const { If } = Condition;
const { Group } = Radio;

@connect(mapStateToProps)
class RuleCombined extends Component {

  state = {
    isEditing: false,
    summaryTypeCode: 'NOT_SUMMARY',
    data: [],
    saveLoading: false
  };

  componentDidMount() {
    const { infoData } = this.props;
    this.setState({ loading: true });
    credentialService.getCombinedRule({
      journalTemplateId: infoData.id
    }).then(res => {
      this.setState({ summaryTypeCode: res.data.summaryTypeCode || 'NOT_SUMMARY', data: res.data.configDists || [], loading: false })
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({ loading: false });
    })
  }

  changeEdit = () => {
    const { isEditing } = this.state;
    this.setState({isEditing: !isEditing});
  };

  options = [
    { title: messages('finance-2.key76')/*不合并*/, key: 'NOT_SUMMARY' },
    { title: messages('finance-2.key77')/*借方合并*/, key: 'SUMMARY_DEBIT' },
    { title: messages('finance-2.key78')/*贷方合并*/, key: 'SUMMARY_CREDIT' },
    { title: messages('finance-2.key79')/*借贷合并*/, key: 'SUMMARY_DEBIT_AND_CREDIT' }
  ];

  columns = [
    { title: messages('finance-2.key80')/*科目编码*/, dataIndex: 'distCode' },
    { title: messages('finance-2.key81')/*科目名称*/, dataIndex: 'distName' },
    {
      title: messages('common.operation')/*操作*/, dataIndex: 'operator',
      render: (value, record) => <a onClick={() => this.handleDelete(record)}>{messages('common.delete')/*删除*/}</a>
    }
  ];

  handleChange = key => {
    let { data, summaryTypeCode } = this.state;
    let value = key.target.value;
    value !== summaryTypeCode && (data = []);
    this.setState({ summaryTypeCode: value, data });
  };

  handleAdd = () => {
    const { infoData } = this.props;
    const { data } = this.state;
    ListSelector.open({
      type: 'select_object',
      extraParams: {
        setOfBooksId: infoData.setOfBooksId
      }
    }, this).then(itemList => {
      itemList.forEach(item => !data.has(item, (a, b) => a.id === b.distId) && (data.push({
        distId: item.id,
        distCode: item.accountCode,
        distName: item.accountName
      })));
      this.setState({ data });
    })
  };

  handleDelete = record => {
    const { data } = this.state;
    if (record.id) {
      this.setState({ loading: true });
      credentialService.deleteRuleCombined(record.id).then(() => {
        data.deleteObj(record, 'distId');
        this.setState({ data, loading: false });
      }).catch(e => {
        this.setState({ loading: false });
        message.error(e.response.data.message);
      });
    } else {
      data.deleteObj(record, 'distId');
    }
  };

  handleSave = () => {
    const { data, summaryTypeCode } = this.state;
    const { infoData, tenant, loginUser } = this.props;
    this.setState({ saveLoading: true });
    credentialService.saveCombinedRule({
      journalTemplateId: infoData.id,
      summaryTypeCode,
      tenantId: tenant.id,
      operatorOid: loginUser.userOID,
      configDists: data
    }).then(res => {
      this.setState({ saveLoading: false, summaryTypeCode: res.data.summaryTypeCode, data: res.data.configDists });
      message.success(messages('common.operate.success')/*操作成功*/);
      this.changeEdit();
    }).catch(e => {
      this.setState({ saveLoading: false });
      message.error(e.response.data.message);
    })
  };

  render() {
    const { isEditing, data, summaryTypeCode, saveLoading, loading } = this.state;
    return (
      <Spin spinning={loading}>
        <div>
          <div>
            <If value={isEditing}>
              <Button onClick={this.handleSave} type='primary' loading={saveLoading}>{messages('common.ok')/*确定*/}</Button>
              <Button onClick={this.changeEdit} style={{marginLeft: '10px'}}>{messages('common.cancel')/*取消*/}</Button>
            </If>
            <If value={!isEditing}>
              <Button onClick={this.changeEdit} type='primary'>{messages('common.edit')/*编辑*/}</Button>
            </If>
          </div>
          <div style={{ margin: '10px 0px' }}>
            <Group onChange={this.handleChange} disabled={!isEditing} value={summaryTypeCode}>
              {this.options.map(item => <Radio value={item.key}>{item.title}</Radio>)}
            </Group>
          </div>
          {
            summaryTypeCode !== 'NOT_SUMMARY' && (
              <div>
                <div style={{ marginBottom: '10px' }}><Button type={'primary'} onClick={this.handleAdd}>{messages('finance-2.key82')/*新建例外科目*/}</Button></div>
                <Table
                  columns={this.columns}
                  dataSource={data}
                  rowKey="distId"
                  pagination={false}
                />
              </div>
            )
          }
        </div>
      </Spin>
    )
  }

}

function mapStateToProps(state){
  return {
    loginUser: state.login.loginUser,
    tenant: state.login.tenant
  }
}

export default RuleCombined
